jQuery(function($) {
    let userGridHeight = getGridHeight();

    let gridSelector = "#gridTable", pagerSelector = "#gridPager";
    let parentColumn = $(gridSelector).closest('[class*="col-"]');
    //resize to fit page size
    $(window).on('resize.jqGrid', function () {
        $(gridSelector).jqGrid( 'setGridWidth', parentColumn.width());
    });

    //resize on sidebar collapse/expand
    $(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
        if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
            //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
            setTimeout(function() {
                $(gridSelector).jqGrid( 'setGridWidth', parentColumn.width());
            }, 20);
        }
    });

    jQuery(gridSelector).jqGrid({
        url : '/sameCityUser/listAppUser',
        jsonReader : {
            root: "list",    //数据集
            page: 'pageNum', //当前页号
            total: 'pages',  //总页数
            records: "total" //总记录数
        },
        rownumbers: true,
        mtype : "post",
        datatype: 'json',
        height: userGridHeight,
        colNames:['用户ID','用户名','昵称', '状态', '性别','邮箱','手机'],
        colModel:[
            {name:'userId',index:'userId', width:60},
            {name:'userName',index:'userName',width:90},
            {name:'nickName',index:'nickName', width:150},
            {name:'status',index:'status', width:70, formatter: function(cellvalue, options, rowObj){
                if (cellvalue == null || cellvalue == ''){
                    return '';
                }
                if (cellvalue != '0' && cellvalue != '1'){
                    return cellvalue;
                }
                let statusName = cellvalue == '0' ? '正常' : '已冻结';
                let statusStr = '<div style="float: left;margin-top: 3px;">'+ statusName + '</div>&nbsp;' +
                    '<input type="checkbox" value="' + cellvalue + '" offval="' + (cellvalue == '0' ? 1 : 0) + '" ' +
                    'id="status' + rowObj.userId + '" name="userStatusSwitch" role="checkbox" class="ace ace-switch ace-switch-5">'+
                '<span class="lbl user-status-switch"></span>';
                return statusStr;
            }},
            {name:'sex',index:'sex', width:90,formatter: function(cellValue, options, rowObject){
                if (cellValue == '0'){
                    return '男';
                }else if (cellValue == '1'){
                    return '女';
                }
                return '';
            }},
            {name:'email',index:'email', width:100},
            {name:'phone',index:'phone', width:100}
        ],
        viewrecords : true,
        rowNum:10,
        rowList:[10,20,30],
        pager : pagerSelector,
        altRows: true,
        loadComplete : function() {
            let table = this;
            setTimeout(function(){
                updatePagerIcons(table);
            }, 0);
            let statusSwitch = $("input[name='userStatusSwitch']");
            statusSwitch.each(function () {
                if ($(this).val() == '1'){
                    $(this).parent().parent().addClass('freezed');
                    $(this).click();
                }
            });
            statusSwitch.click(function () {
                return freezeStatus(this);
            });
        }
    });
    //trigger window resize to make the grid get the correct size
    $(window).triggerHandler('resize.jqGrid');

    //navButtons
    jQuery(gridSelector).jqGrid('navGrid',pagerSelector,
        { 	//navbar options
            edit: false,
            editicon : 'ace-icon fa fa-pencil blue',
            add: false,
            addicon : 'ace-icon fa fa-plus-circle purple',
            del: false,
            delicon : 'ace-icon fa fa-trash-o red',
            search: true,
            searchicon : 'ace-icon fa fa-search orange',
            refresh: true,
            refreshicon : 'ace-icon fa fa-refresh green',
            view: false,
            viewicon : 'ace-icon fa fa-search-plus grey',
        }
    );

    //replace icons with FontAwesome icons like above
    function updatePagerIcons(table) {
        let replacement = {
            'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
            'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
            'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
            'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
        };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
            let icon = $(this);
            let $class = $.trim(icon.attr('class').replace('ui-icon', ''));
            if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
        });
    }
    //查询按钮
    $('#spQuerySysUser').click(function () {
        let sysUserParam = {
            userId: $('#qUserId').val(),
            userName: $('#qUserName').val(),
            phone: $('#qUserPhone').val()
        };
        jQuery(gridSelector).setGridParam({postData:sysUserParam}).trigger("reloadGrid");
    });
});

/**
 * 解冻/冻结操作
 * @param freezeObj 解冻/冻结input对象
 * @returns {boolean} 操作成功，返回true,操作失败，返回false
 */
async function freezeStatus(freezeObj) {
    let oldStatus = $(freezeObj).val(), freezeSuccess = false;
    let tip = oldStatus == '0' ? '冻结' : '解冻';
    let newStatus = oldStatus == '0' ? '1' : '0', freezeId = $(freezeObj).attr('id');
    //同步处理
    await swal({
        title: '确认' + tip,
        text: '您确定要' + tip + '该用户吗？',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        cancelButtonText: '取消',
        confirmButtonText: tip
    }).then(function(isConfirm) {
        if (!isConfirm) {
            return;
        }
        $.ajax({
            type: "POST",
            url: '/sameCityUser/freezeAppUser',
            dataType:'json',
            async: false,
            data:{status: newStatus,userId: freezeId.replace('status','')},
            success: function(freezeResult){
                if (freezeResult == '0'){
                    swal('成功提示',tip + '成功','success');
                    $(freezeObj).attr('value',newStatus).attr('offval',oldStatus);
                    freezeSuccess = true;
                    let newStatusName = newStatus == '0' ? '正常' : '已冻结';
                    $(freezeObj).prev().text(newStatusName);
                    let freezeTd = $(freezeObj).parent();
                    freezeTd.attr('title',newStatusName);
                    if (newStatus == '0'){
                        freezeTd.parent().removeClass('freezed');
                    } else {
                        freezeTd.parent().addClass('freezed');
                    }
                }else if(freezeResult == '1') {
                    swal('失败提示',tip + '失败，参数错误','error');
                }else {
                    swal('失败提示',tip + '失败','error');
                }
            },
            error: function () {
                swal('失败提示',tip + '出错，请稍候再试','error');
            }
        });
    });
    return freezeSuccess;
}
